package com.henz4help.app;

import java.util.List;
import java.util.Locale;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.GestureDetector;
import android.view.GestureDetector.OnDoubleTapListener;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapLoadedCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.henz4help.app.base.BaseActivity;
import com.henz4help.app.common.Constants;
import com.henz4help.app.common.Util;
import com.henz4help.app.db.HenzDBHelper;
import com.henz4help.app.db.domain.PersonalData;

public class 
	MainActivity 
extends 
	BaseActivity 
implements 
 	  OnGestureListener
 	, OnDoubleTapListener
 	, LocationListener
{
	
	private final int MSG_SIGNAL_SEND = 199;
	private final int MSG_BEATING = 299;
	private ImageView mImvMainSettings;
	private ImageView mImvSOS;
	private ImageView mImv911;
	private ImageView mImvSendTxt;
	
	private ImageView mImvAlert;
	private ImageView mImvSesSay;
	
	private SignalSendReceiver mReceiver;
	private GestureDetector mGestureDetector;
	private int mTouchedImageId;
	private int mBeatScope;
	private boolean mBeatingOrder;
	private boolean mBeating;
	
	private GoogleMap mmap;
	
	public static String latitude;
	public static String longitude;
	
	public static String address;
	
	
	/*
	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}
	*/
	
	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_activity);
		//checkGPS();
		setWarnMap();
		
		mBeating = false;
		mBeatingOrder = false;
		mBeatScope = 0;
		
		mReceiver = new SignalSendReceiver();
		mGestureDetector = new GestureDetector(this);
		mGestureDetector.setOnDoubleTapListener(this);
		setComponent();
		//setRegid();
	}
	

	@Override
	protected void onDestroy() {
		super.onDestroy();
		HenzDBHelper.destroyHenzDBHelper();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
		//checkPlayServices();
		setWarnMap();
	}

	@Override
	protected void onStart() {
		super.onStart();
		setWarnMap();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		mGestureDetector.onTouchEvent(event);
		return super.onTouchEvent(event);
	}

	private void setComponent() {
		mImvMainSettings = (ImageView)findViewById(R.id.imvMainSettings);
		mImvMainSettings.setOnTouchListener(mTouchListener);

		mImvAlert = (ImageView)findViewById(R.id.imvAlert);
		mImvAlert.setOnTouchListener(mTouchListener);

		mImvSesSay = (ImageView)findViewById(R.id.imvSesSay);
		mImvSesSay.setOnTouchListener(mTouchListener);
		
		mImvSOS = (ImageView)findViewById(R.id.imvSOS);
		mImv911 = (ImageView)findViewById(R.id.imv911);
		mImvSendTxt = (ImageView)findViewById(R.id.imvSendTxt);
		
		
		mImvSOS.setOnTouchListener(mTouchListener);
		mImv911.setOnTouchListener(mTouchListener);
		mImvSendTxt.setOnTouchListener(mTouchListener);
		
	}
	
    
    /*
    private LocationManager mLocationManager;
    private String provider;
	private LocationProvider mLocationGpsProvider;
	private LocationProvider mLocationNetworkProvider;
	
	private static final int GPS_PROVIDER = 1;
	private static final int NETWORK_PROVIDER = 2;
	private int whichProvider;
	
	double lat = 0;
	double lnt = 0;
	
	 GPS Listener 
	private LocationListener gpsListener = new LocationListener() {
		@Override
		public void onLocationChanged(Location location) {
			Util.Log("LocSenderService : gpsListnener onLocationChanged()");
			lat = location.getLatitude();
			lnt = location.getLongitude();
		}

		@Override
		public void onProviderDisabled(String provider) {
			Util.Log("LocSenderService : gpsListnener onProviderDisabled()");
		}

		@Override
		public void onProviderEnabled(String provider) {
			Util.Log("LocSenderService : gpsListnener onProviderEnabled()");
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			Util.Log("LocSenderService : gpsListnener onStatusChanged()");
		}
	};
	
	
	
	 * Network Listener
	 
	private LocationListener netListener = new LocationListener() {
		@Override
		public void onLocationChanged(Location location) {
			Util.Log("LocSenderService : netListnener onLocationChanged()");
			lat = location.getLatitude();
			lnt = location.getLongitude();
		}

		@Override
		public void onProviderDisabled(String provider) {
			Util.Log("LocSenderService : netListnener onProviderDisabled()");
		}

		@Override
		public void onProviderEnabled(String provider) {
			Util.Log("LocSenderService : netListnener onProviderEnabled()");
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			Util.Log("LocSenderService : netListnener onStatusChanged()");
		}
	};
	
	private void setupGPS() {
		mLocationGpsProvider = mLocationManager.getProvider(LocationManager.GPS_PROVIDER);
		
		if(whichProvider == NETWORK_PROVIDER)
			mLocationManager.removeUpdates(netListener);
		
		mLocationManager.requestLocationUpdates(mLocationGpsProvider.getName(), 1000, 0, gpsListener);
		whichProvider = GPS_PROVIDER;
	}
	
	
	private void setupNET() {
		mLocationNetworkProvider = mLocationManager.getProvider(LocationManager.NETWORK_PROVIDER);
		
		if(whichProvider == GPS_PROVIDER)
			mLocationManager.removeUpdates(gpsListener);
		
		mLocationManager.requestLocationUpdates(mLocationNetworkProvider.getName(), 1000, 0, netListener);
		whichProvider = NETWORK_PROVIDER;
	}
    */
	
	private LocationManager mLocationManager;
	
	protected void checkGPS(){
		mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		
		if (!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(R.string.gpsDisabledMessage)
					.setCancelable(false)
					.setPositiveButton("Yes",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									Intent intent = new Intent(
											Settings.ACTION_LOCATION_SOURCE_SETTINGS);
									startActivity(intent);
								}
							})
					.setNegativeButton("No",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									// dialog.cancel();
									onBackPressed();
								}
							});
			AlertDialog alert = builder.create();
			alert.show();
		}
	}
	
	protected void setCurrentLocation(){
		Location loc = null;
		loc = mmap.getMyLocation();
    	if(loc != null){
        	LatLng latLng = null;
        	
        	latitude = String.valueOf(loc.getLatitude());
        	longitude = String.valueOf(loc.getLongitude());
        	
        	latLng = new LatLng( loc.getLatitude(), loc.getLongitude() );
        	mmap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        	
        	
        	//Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
        	Geocoder geocoder = new Geocoder(
        				  mContext
        				//, Locale.getDefault()
        				, Locale.US
        			);
        	
        	List<Address> addrList = null;

        	try {
				addrList = geocoder.getFromLocation(loc.getLatitude(),
				        loc.getLongitude(), 1);
			} catch (Exception e) {
			}
        	
        	if (addrList != null && addrList.size() > 0) {
                // Get the first address
                Address addrObj = addrList.get(0);
                /*
                 * Format the first line of address (if available),
                 * city, and country name.
                 */
                
                int maxNum = addrObj.getMaxAddressLineIndex();
                address = "";
                for( int i = 0; i < maxNum; i ++ ){
                	if( i != 0 ){
                		address += " ";
                	}
                	address += addrObj.getAddressLine(i);
                }
                
                /*
                address = String.format(
                        "%s, %s, %s",
                        // If there's a street address, add it
                        address,
                        // Locality is usually a city
                        addrObj.getLocality(),
                        // The country of the address
                        addrObj.getCountryName()
                );
                */
            }

        	
        	
    	}
	}
	
	
	protected void setWarnMap(){
		
		mmap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.warnMap)).getMap();
    	mmap.animateCamera(CameraUpdateFactory.zoomTo(13));
		mmap.setMyLocationEnabled(true);
		mmap.setOnMapLoadedCallback(new OnMapLoadedCallback(){
			@Override
			public void onMapLoaded() {
				setCurrentLocation();
			}
		});
		setCurrentLocation();
	}
	
	private View.OnTouchListener mTouchListener = new View.OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			mTouchedImageId = v.getId();			
			return false;
		}
	};

	@Override
	public boolean onDown(MotionEvent arg0) {
		Intent intent = null;
		if(mTouchedImageId == R.id.imvMainSettings) {
			intent = new Intent(MainActivity.this, SettingsActivity.class);
		}else if(mTouchedImageId == R.id.imvAlert) {
			intent = new Intent(MainActivity.this, AlertActivity.class);
		}else if(mTouchedImageId == R.id.imvSesSay) {
			intent = new Intent(MainActivity.this, SeeSayActivity.class);
		}
		if(intent != null){
			startActivity(intent);
			mTouchedImageId = -1;
			return true;
		}
		return false;
	}

	@Override
	public boolean onFling(MotionEvent arg0, MotionEvent arg1, float arg2, float arg3) {
		return false;
	}

	@Override
	public void onLongPress(MotionEvent arg0) {		
	}

	@Override
	public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2, float arg3) {
		return false;
	}

	@Override
	public void onShowPress(MotionEvent arg0) {
		
	}
	
	protected int tabCnt = 0;
	protected long lastTime = 0;
	protected long curTime = 0;
	@Override
	public boolean onSingleTapUp(MotionEvent arg0) {
		/*
		if(mTouchedImageId == R.id.imvSOS) {
			long gap = 0;
			curTime = System.currentTimeMillis();
			gap = curTime - lastTime;
			lastTime = curTime;
			if( gap < 1000 ){
				tabCnt++;
			}else{
				tabCnt = 1;
			}
			if(tabCnt == 3){
				tabCnt = 0;
				Util.Log( "onTripleTapUp[" + tabCnt + "][" + gap + "]====================" );
				sendMsg();
			}else{
				Util.Log( "onSingleTapUp[" + tabCnt + "][" + gap + "]==========" );
			}
		}
		*/
		return false;
	}
	protected boolean sendMsgOrg(){
		/*
		mImvSOS = (ImageView)findViewById(R.id.imvSOS);
		mImv911 = (ImageView)findViewById(R.id.imv911);
		mImvSendTxt = (ImageView)findViewById(R.id.imvSendTxt);
		 */
		mTouchedImageId = -1;
		
		if(mBeating)
			return true;
		
		if(mDatabaseHelper.retrievePersonalData() == null) {
			Util.showDialogBox(MainActivity.this, null, "There are no personal data.");
			return true;
		}
		
		//mImvSOS.setImageResource(R.drawable.main_calling);
		mBeating = true;
		mBeatingOrder = false;
		mBeatScope = 0;
		new Beater().start();
		
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(Constants.ACTION_SIGNAL_SEND);
		registerReceiver(mReceiver, intentFilter);
		 
		Intent intent = new Intent("com.henz4help.app.locsenderservice");
		startService(intent);
		
		return true;
	}
	
	@Override
	public boolean onDoubleTap(MotionEvent arg0) {
		boolean returnValue = false;
		
		if(mTouchedImageId == R.id.imvSOS) {
			Util.Log( "onDoubleTap SOS==========" );
			returnValue = sendMsg( 0 );
		}else if(mTouchedImageId == R.id.imv911) {
			Util.Log( "onDoubleTap 911==========" );
			returnValue = sendMsg( 1 );
			String url = "tel:4694713051";
			Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(url));
			startActivity( callIntent );
		}else if(mTouchedImageId == R.id.imvSendTxt) {
			Util.Log( "onDoubleTap SendTxt==========" );
			returnValue = sendMsg( 2 );
		}
		
		return returnValue;
	}
	
	protected boolean sendMsg( int MsgType ){
		
		//Bundle bund = null;
		
		/*
		mImvSOS = (ImageView)findViewById(R.id.imvSOS);
		mImv911 = (ImageView)findViewById(R.id.imv911);
		mImvSendTxt = (ImageView)findViewById(R.id.imvSendTxt);
		 */
		if(mBeating){
			return true;
		}
		mBeating = true;
		
		Intent intent = null;
		mTouchedImageId = -1;
		
		/*
		returnValue.put(HenzDB.TPersonalData.LATITUDE , data.latitude);
		returnValue.put(HenzDB.TPersonalData.LONGITUDE, data.longitude);
		 */
		
		PersonalData pData = null;
		
		
		pData = mDatabaseHelper.retrievePersonalData();
		
		if(pData == null) {
			Util.showDialogBox(MainActivity.this, null, "There are no personal data.");
			mBeating = false;
			return true;
		}
		
		
		pData.latitude = latitude;
		pData.longitude = longitude;
		pData.address = address;
		
		mDatabaseHelper.updatePersonalData(pData);
		
		//mImvSOS.setImageResource(R.drawable.main_calling);
		
		mBeatingOrder = false;
		mBeatScope = 0;
		new Beater().start();
		
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(Constants.ACTION_SIGNAL_SEND);
		registerReceiver(mReceiver, intentFilter);
		 
		intent = new Intent("com.henz4help.app.locsenderservice");
		
		startService(intent);
		
		if(mTouchedImageId == R.id.imv911) {
			Util.Log( "onDoubleTap 911==========" );
			String url = "tel:4694713051";
			Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(url));
			startActivity( callIntent );
		}
		
		return true;
	}
	
	@Override
	public boolean onDoubleTapEvent(MotionEvent arg0) {
		return false;
	}

	@Override
	public boolean onSingleTapConfirmed(MotionEvent arg0) {
		return false;
	}
	
	private class SignalSendReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context ctx, Intent intent) {
			int extravalue = intent.getIntExtra(Constants.EXTRA_SIGNAL_SEND, 0);
			if(extravalue == Constants.VALUE_SIGNAL_SEND) {
				Message msg = Message.obtain();
				msg.what = MSG_SIGNAL_SEND;
				mHandler.sendMessage(msg);
			}
		}
	}
	
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what) {
			case MSG_SIGNAL_SEND:
				mBeating = false;
				//mImvSOS.setImageResource(R.drawable.main_distress);
				mImvSOS.setPadding(0, 0, 0, 0);
				mImvSOS.invalidate();
				unregisterReceiver(mReceiver);
				
				//Util.showDialogBox(MainActivity.this, null, "Signal has been sent. Stay Safe!");
				
				
				Intent intent = null;
				intent = new Intent(MainActivity.this, GcmReportActivity.class);
				startActivity(intent);
				
				break;
			case MSG_BEATING:
				if(mBeating) {
					if(mBeatingOrder) {
						if(mBeatScope > 50) {
							mBeatingOrder = false;
						} else {
							mBeatScope += 10;
						}
					} else {
						if(mBeatScope <= 0) {
							mBeatingOrder = true;
						} else {
							mBeatScope -= 10;
						}
					}
					mImvSOS.setPadding(mBeatScope, mBeatScope, mBeatScope, mBeatScope);
					mImvSOS.invalidate();
				}
				break;
			}
		}		
	};
	
	private class Beater extends Thread {
		@Override
		public void run() {
			while(mBeating) {
				try {
					Thread.sleep(100);
					Util.Log("LocSenderService : Worker is working!!");
				} catch (InterruptedException e) {
					Util.Log("LocSenderService : " + e.toString());
				}
				Message msg = Message.obtain();
				msg.what = MSG_BEATING;
				mHandler.sendMessage(msg);
			}
		}		
	}

	@Override
	public void onLocationChanged(Location arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}
}
